package com.hxalex.simulationhandle.accessbilityService.receiver.wifi.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.support.annotation.Nullable;
import android.util.Log;

import com.hxalex.simulationhandle.accessbilityService.manger.WifiManger;

import org.greenrobot.eventbus.EventBus;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by hx_Alex on 2018/5/27.
 */

public class WifiInfoService extends IntentService {
    public static final int MAX_COUNT = 20;
    public static final String WIFI_STATE = "WIFI_STATE";
    public static final String WIFI_PING = "WIFI_PING";
    public int checkCount = 0;
    private int UnknownHostExceptionCount=0;
    private WifiManger wifiManger;
    private boolean isStartExeCute=false;
    public WifiInfoService() {
        super("WifiInfoService");
        wifiManger = WifiManger.getWifiManger(this);
    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i("WifiInfoService", "已开启WifiInfoService");
        String action = intent.getAction();
        if (action.equals(WIFI_STATE)) {
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            boolean wifiEnabled = false;
            while (checkCount < MAX_COUNT) {
                wifiEnabled = wifiManager.isWifiEnabled();
                if (wifiEnabled) {
                    checkCount = 0;
                    postMsg(true);
                    break;
                }
                checkCount++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (!wifiEnabled) {
                checkCount = 0;
                postMsg(false);
            }
        } else if (action.equals(WIFI_PING)) {
            isExit = false;
            checkCount = 0;
            searchWiFiUsability();
        }
    }


    public void postMsg(Boolean isEnable) {
        EventBus.getDefault().post(isEnable);
    }

    public void postMsg(Integer state) {
        EventBus.getDefault().post(state);
    }

    private boolean isExit = false;

    private void searchWiFiUsability() {

        while (!isExit && checkCount < 40) {
            if(isStartExeCute) return;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            if (!wifiManger.isWifi()) {
                checkCount++;
                continue;
            }
            Log.i("WifiInfoService", "wifi 已经连接.....开始检查wifi是否可以正常使用");
            isStartExeCute=true;
            
            try {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                Request request = new Request.Builder()
                        .url("https://www.baidu.com")//请求接口。如果需要传参拼接到接口后面。
                        .build();//创建Request 对象
                Response response = null;
                response = client.newCall(request).execute();//得到Response 对象
                if (response.isSuccessful() && response.code()==200) {
                    postMsg(0);//0->wifi可用 1->需要网络验证  2->wifi不可用
                } else {
                    postMsg(2);//0->wifi可用 1->需要网络验证  2->wifi不可用
                }
                isExit = true;
            } catch (Exception e) {
                if(e.getClass().toString().contains("SocketTimeoutException"))
                {
                    postMsg(2);//0->wifi可用 1->需要网络验证  2->wifi不可用  
                    isStartExeCute=false;
                    isExit = true;
                }else if(e.getClass().toString().contains("UnknownHostException"))
                {
                    UnknownHostExceptionCount++;
                    isStartExeCute=false;
                    if(UnknownHostExceptionCount>5)
                    {
                        postMsg(2);//0->wifi可用 1->需要网络验证  2->wifi不可用  
                        isStartExeCute=false;
                        isExit = true;
                        UnknownHostExceptionCount=0;
                    }
                }
                e.printStackTrace();
            }
            
        }
        if (checkCount >= 40) {
            Log.i("WifiInfoService","连接超时");
            postMsg(3);
            isStartExeCute=false;
            isExit = true;
        }

       

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
